package chen.web.back.client;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.google.gwt.http.client.URL;

public class FormDataBuilder {

	private Map<String, String[]> parameterMap = new HashMap<String, String[]>();

	public FormDataBuilder addProperty(String name, String value) {
		String[] oldValues = parameterMap.get(name);
		if(oldValues == null || oldValues.length == 0){
			parameterMap.put(name, new String[]{value});
		}else{
			ArrayList<String> list = new ArrayList<String>();
			list.addAll(Arrays.asList(oldValues));
			list.add(value);
			parameterMap.put(name, list.toArray(new String[0]));
		}
		return this;
	}
	
	public FormDataBuilder setProperty(String name, String[] values) {
		parameterMap.put(name, values);
		return this;
	}

	public String toQueryString() {
		StringBuffer sb = new StringBuffer();
		Set<Map.Entry<String,String[]>> entrySet = parameterMap.entrySet();
		for(Map.Entry<String, String[]> entry : entrySet){
			String key = entry.getKey();
			String[] values = entry.getValue();
			for(String value : values){
				if(sb.length() > 0) {
					sb.append("&");
				}
				sb.append(URL.encode(key)).append("=").append(URL.encode(value == null ? "": value));
			}
		}
		return sb.toString();
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return toQueryString();
	}

	public String toJSONString() {
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		Set<Map.Entry<String,String[]>> entrySet = parameterMap.entrySet();
		for(Map.Entry<String, String[]> entry : entrySet){
			String key = entry.getKey();
			String[] values = entry.getValue();
			for(String value : values){
				if(sb.length() > 1) {
					sb.append(",");
				}
				sb.append('"').append(key).append('"').append(":").append('"').append(value).append('"');
			}
		}
		sb.append("}");
		return sb.toString();
	}

}
